﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class GetMainCommandHander : IRequestHandler<GetMainCommand, ApiPaging<List<GetMainDto>>>
    {

        private readonly IMapper mapper;
        private readonly ILogger<GetMainCommandHander> logger;
        private readonly ISqlSugarClient db;

        public GetMainCommandHander(IMapper mapper, ILogger<GetMainCommandHander> logger, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.db = db;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<List<GetMainDto>>> Handle(GetMainCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<List<GetMainDto>> result = new ApiPaging<List<GetMainDto>>();

            var list = db.Queryable<Main>()
                .InnerJoin<User>((a, u) => a.UserId == u.UserId)
                .Where((a, u) => a.IsDelete == false)
                .Select((a, u) => new GetMainDto
                {
                    MainId = a.MainId,
                    Name = a.Name,
                    Sex = a.Sex,
                    Address = a.Address,
                    UserId = a.UserId,
                    CreateTime = a.CreateTime,
                    IsDelete = a.IsDelete,
                    UserName = u.UserName,
                    Password = u.UserName,
                    UserNickName = u.UserNickName,
                    MarketName = a.MarketName,
                    EconomizeName = a.EconomizeName,
                    CityName = a.CityName,
                });

            result.Code = ApiEnum.显示成功;
            result.Msg = ApiEnum.显示成功.ToString();

            result.TotalCount = list.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            var entity = list.OrderBy(a => a.MainId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Data = mapper.Map<List<GetMainDto>>(entity);

            return Task.FromResult(result);
        }
    }
}
